//
//  TravelDetailTVController.m
//  WildDonkey
//
//  Created by 佟小波 on 15/3/27.
//  Copyright (c) 2015年 lanou. All rights reserved.
//

#import "TravelDetailTVController.h"
#import "TravelDetailTVCell.h"
#import "TravelDetail.h"
#import "TravelImpressionController.h"
#import "Travel.h"
#import "UIScrollView+TwitterCover.h"
#import "PhotoTVController.h"
#import "MJRefresh.h"

static CGFloat kImageOriginHight = 200;

static CGFloat kTempHeight = 80.0f;

static const CGFloat MJDuration = 2.0;

@interface TravelDetailTVController ()


@property (nonatomic,retain) NSMutableArray *travelDetailArr;
@property (nonatomic,retain) NSMutableData *receivedData;
@property (nonatomic,retain) NSArray *signArr;
@property (nonatomic,assign) NSInteger signIndex;
@property (nonatomic,retain) UIScrollView *headerScroll;
@property (nonatomic,retain) UIActivityIndicatorView *activityIndicator;


@end

@implementation TravelDetailTVController

- (void)dealloc
{
    [_receivedData release];
    [_travelDetailArr release];
    [_signArr release];
    [_headerScroll release];
  
    [super dealloc];
}



- (void)MJRefresh
{
    NSLog(@"mjrefresh");
    // 1.下拉刷新
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
        [self loadNewData];
    }];
    
    // 马上进入刷新状态
    [self.tableView.legendHeader beginRefreshing];
    
    //    [self performSelector:@selector(headerRereshing) withObject:self.tableView.tableHeaderView afterDelay:2.0];
    
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    //    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    
}




#pragma mark - 数据处理相关
#pragma mark 下拉刷新数据
- (void)loadNewData
{
    // 1.添加假数据
    //    for (int i = 0; i<5; i++) {
    //        [self.data insertObject:MJRandomData atIndex:0];
    //    }
    
    // 2.模拟2秒后刷新表格UI（真实开发中，可以移除这段gcd代码）
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(MJDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.tableView reloadData];
        
        // 拿到当前的下拉刷新控件，结束刷新状态
        [self.tableView.header endRefreshing];
    });
}



//图片加载的菊花
- (void) loading{
    _activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    _activityIndicator.frame=[UIScreen mainScreen].bounds;
    _activityIndicator.center=CGPointMake(self.view.center.x, self.view.center.y-30);
    _activityIndicator.color=[UIColor grayColor];
    [self.view addSubview:_activityIndicator];
    [_activityIndicator startAnimating];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    self.receivedData = [NSMutableData data];
    
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    //    NSLog(@"---%d",[data length]);
    [self.receivedData appendData:data];
    //    NSLog(@"--------%.2f",1.0*[self.receivedData length]/self.totalLength);
    
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    
    [_activityIndicator stopAnimating];
    
    NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:self.receivedData options:0 error:nil];
    NSArray *data = [resultDic objectForKey:@"data"];
    //    NSLog(@"%@",data);
    self.travelDetailArr = [NSMutableArray arrayWithCapacity:[data count]];
    
    for (NSDictionary *event in data) {
        TravelDetail *travelDetail = [[TravelDetail alloc]init];
        [travelDetail setValuesForKeysWithDictionary:event];
        
        [self.travelDetailArr addObject:travelDetail];
        [travelDetail release];
    }
    
    [self.tableView reloadData];//相当于刷新
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"%@",error);
}



- (void)setHeaderScrollView
{
//    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
//    [scrollView setContentSize:CGSizeMake(self.view.bounds.size.width, 600)];
//    [scrollView addTwitterCoverWithImage:[UIImage imageNamed:@"cover.png"]];
//    [self.view addSubview:scrollView];
    
//    [scrollView addSubview:({
//        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, CHTwitterCoverViewHeight, self.view.bounds.size.width - 40, 600 - CHTwitterCoverViewHeight)];
//        label.numberOfLines = 0;
//        label.font = [UIFont systemFontOfSize:22];
//        label.text = @"TwitterCover is a parallax top view with real time blur effect to any UIScrollView, inspired by Twitter for iOS.\n\nCompletely created using UIKit framework.\n\nEasy to drop into your project.\n\nYou can add this feature to your own project, TwitterCover is easy-to-use.";
//        label;
//    })];

}



- (void)viewDidLoad {
    [super viewDidLoad];
    //    self.view.backgroundColor=[UIColor blueColor];
    
    [self loading];
    
    [self MJRefresh];
    
    //设置头部下拉拉伸图片
    [self setHeaderScrollView];
    
    Travel *t=[[Travel alloc]init];
    t=self.travel;
//    NSLog(@"++++after:%@",t.mtid);
    
    self.navigationItem.title = @"景点";
    UIImageView *bgView = [[UIImageView alloc] init] ;
    bgView.image = [UIImage imageNamed:@"background"];
    self.tableView.backgroundView = bgView;
    
    
    _signArr=@[@"aad177c204b128f397c31fedd811f30435751741",@"189d0b6fb14cfe4c8b88b112cb324fe010fbe761",@"b8b2614341e8532b631db98be2fa5287c841d265",@"3131df31a4a1888962683583c15ce7827dccea97",@"896c3e93443f43195f3ec5f48e6207f171ce54fd",@"ec7f0f59dadfbf7c649a7334dee6aa21928b9e2a",@"d3a209e51b66d9aa0c321fee45957cc0962788a8",@"b192ab077b02077b0d2e17c98900aaab2d77d613",@"2162f0da63174f57f8d98c57390bcfc2600f614d",@"a2b8fa78e36c44c11d01726d5128873e07e6b964",@"88c4edcccd1e5d8a448a8d1152948469df68005e"];
    
    NSString *str1=[NSString stringWithFormat:@"http://www.roadqu.com/api/mobile/qunawan/tour/seasonfunplacelist&a_t=1427359626000&token=551125988bbb2&mtid=%@",t.mtid];
    NSString *str2=[NSString stringWithFormat:@"&startpos=0&eachpage=5&issue=%@",t.issue];
    NSString *str3=[NSString stringWithFormat:@"&sign=%@",[NSString stringWithFormat:@"%@",_signArr[_signIndex+1]]];
    
    NSString *str = [[str1 stringByAppendingString:str2] stringByAppendingString:str3];
    
//    NSLog(@"%@",str);
    
    NSURL *url = [NSURL URLWithString:str];
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
    [[[NSURLConnection alloc]initWithRequest:request delegate:self]autorelease];
    [request release];
    
    

    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return [_travelDetailArr count];
}


//行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 300;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    //url中sign数组中下标
    _signIndex=indexPath.row;
    
    tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    
    TravelDetail *detail=_travelDetailArr[indexPath.row];
    
    static NSString *identifier = @"travelDetail";
    TravelDetailTVCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[[TravelDetailTVCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] autorelease];
        
    }
    // Configure the cell...
    cell.backgroundColor = [UIColor clearColor];
    cell.travelDetail=detail;
    
    //无色
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TravelImpressionController *travelImpression=[[[TravelImpressionController alloc]initWithStyle:UITableViewStyleGrouped]autorelease];
    travelImpression.detail=_travelDetailArr[indexPath.row];
    
    
//    PhotoTVController *photoController=[[PhotoTVController alloc]init];
//    photoController.code=@"aaaa";
    
    [self.navigationController pushViewController:travelImpression animated:YES];
    
    //[self.view removeFromSuperview];
}



//
//#pragma mark 设置header高度
//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
//{
//    return 100;
//}
//
//#pragma mark 设置header内容
//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//{
//    return _headerScroll;
//}



/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 } else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */


@end
